﻿
using System;
using System.Text;
using System.Threading.Tasks;

using DotNetty.Wraper;
using Examples.Common;
using Microsoft.Extensions.Logging;

namespace TcpSocket.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            ILogger _logger = new CNative.Logging.ConfigLogger();

            var option = new ServerOption();
            option.Port = Examples.Common.ServerSettings.Port;
            option.UseLibuv = Examples.Common.ServerSettings.UseLibuv;
            if (Examples.Common.ServerSettings.IsSsl)
            {
                option.Certificate = System.IO.Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx");
                option.CertificatePassword = "password";
            }
            var theServerBuild = SocketBuilderFactory.GetTcpSocketServerBuilder(option)
             .OnConnectionClose((server, connection) =>
             {
                 _logger.LogInformation($"连接关闭,连接名[{connection.ConnectionName}],当前连接数:{server.GetConnectionCount()}");
             })
             .OnException(ex =>
             {
                 _logger.LogError($"服务端异常:{ex.Message}");
             })
             .OnChannelRegistered((server, channel) =>
             {
                 _logger.LogDebug("ChannelUnregistered: " + channel.Id);
             })
             .OnChannelRegistered((server, channel) =>
             {
                 _logger.LogDebug("ChannelRegistered: " + channel.Id);
             })
             .OnNewConnection((server, connection) =>
             {
                 connection.ConnectionName = $"名字{connection.ConnectionId}";
                 _logger.LogInformation($"新的连接[{connection.ClientAddress.Address.MapToIPv4().ToString()}]:{connection.ConnectionName},当前连接数:{server.GetConnectionCount()}");
             })
             .OnRecieve((server, connection, bytes) =>
             {
                 _logger.LogInformation($"服务端:数据{Encoding.UTF8.GetString(bytes)}");
                 connection.Send(bytes);
             })
             .OnSend((server, connection, bytes) =>
             {
                 _logger.LogInformation($"向连接名[{connection.ConnectionName}]发送数据:{Encoding.UTF8.GetString(bytes)}");
             })
             .OnServerStarted(server =>
             {
                 _logger.LogInformation($"服务启动");
             });
            var theServer = await theServerBuild.BuildAsync((pipeline) =>
            {
                pipeline.AddLast("framing-enc", new DotNetty.Codecs.LengthFieldPrepender(2));
                pipeline.AddLast("framing-dec", new DotNetty.Codecs.LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
            });

            Console.ReadLine();

            theServer?.Close();
        }
    }
}
